﻿

namespace dianying
{
    using System;
    using System.Collections.Generic;
    using System.Collections.Specialized;
    using System.IO;
    using System.Net;
    using System.Net.NetworkInformation;
    using System.Net.Sockets;
    using System.Security.Cryptography;
    using System.Text;
    using System.Windows.Forms;

    [Serializable]
    public class DESEncrypt
    {






        private static string ConKey = "1F520EC40D7FDD0E2C517288FA4C5B12";
        private static string PwdKey = "9E437346EBA2CB75FF37234EC8EE35D0";

        /// <summary>
        /// 解密
        /// </summary>
        /// <param name="src"></param>
        /// <returns></returns>
        public static string Decrypt(string src)
        {
            DESEncrypt encrypt = new DESEncrypt();
            return encrypt.DecryptString(src, ByteStringUtil.ByteArrayToHexStr(HashDigest.StringDigest(ConKey)));
        }
   
        private static byte[] Keys = new byte[] { 0x8e, 0x3d, 0x18, 0xe8, 30, 0xa1, 0x6f, 0x5f };
        /// <summary>
        /// 解密
        /// </summary>
        /// <param name="srcData"></param>
        /// <param name="strKey"></param>
        /// <returns></returns>
        public byte[] Decrypt(byte[] srcData, string strKey)
        {
            try
            {
                if ((srcData == null) || (srcData.Length < 1))
                {
                    return null;
                }
                byte[] buffer = HashDigest.StringDigest(strKey, DigestType.MD5);
                SymmetricAlgorithm algorithm = SymmetricAlgorithm.Create("3DES");
                algorithm.Key = buffer;
                algorithm.IV = Keys;
                new DESCryptoServiceProvider();
                MemoryStream stream = new MemoryStream();
                CryptoStream stream2 = new CryptoStream(stream, algorithm.CreateDecryptor(), CryptoStreamMode.Write);
                stream2.Write(srcData, 0, srcData.Length);
                stream2.FlushFinalBlock();
                stream2.Clear();
                return stream.ToArray();
            }
            catch (Exception ex)
            {
                throw ex.InnerException;
            }

        }
        /// <summary>
        /// 解密字符串
        /// </summary>
        /// <param name="srcStr"></param>
        /// <returns></returns>
        public string DecryptString(string srcStr)
        {
            return this.DecryptString(srcStr, this.DefaultKey);
        }
        /// <summary>
        /// 解密字符串
        /// </summary>
        /// <param name="srcString"></param>
        /// <param name="strKey">字符串密匙</param>
        /// <returns></returns>
        public string DecryptString(string srcString, string strKey)
        {
            byte[] srcData = ByteStringUtil.ByteArrayFromHexStr(srcString);
            return Encoding.Default.GetString(this.Decrypt(srcData, strKey));
        }
        private string DefaultKey
        {
            get
            {
                return Encoding.Default.GetString(HashDigest.StringDigest("Ultra.Web.Core.Common-Serct-Key", DigestType.MD5));
            }
        }


    }


    [Serializable]
    public sealed class HashDigest
    {
        public static byte[] FileDigest(string filePath)
        {
            return FileDigest(filePath, DigestType.MD5);
        }

        public static byte[] FileDigest(string filePath, DigestType dgType)
        {
            if (!(!string.IsNullOrEmpty(filePath) && File.Exists(filePath)))
            {
                return null;
            }
            Stream inputStream = File.OpenRead(filePath);
            byte[] buffer = GetHashAlgorithmByType(dgType).ComputeHash(inputStream);
            inputStream.Close();
            return buffer;
        }

        public static HashAlgorithm GetHashAlgorithmByType(DigestType dgType)
        {
            switch (dgType)
            {
                case DigestType.MD5:
                    return MD5.Create();

                case DigestType.SHA1:
                    return SHA1.Create();

                case DigestType.SHA256:
                    return SHA256.Create();

                case DigestType.SHA384:
                    return SHA384.Create();

                case DigestType.SHA512:
                    return SHA512.Create();

                case DigestType.RIPEMD160:
                    return RIPEMD160.Create();
            }
            return null;
        }

        public static byte[] StringDigest(string strSrc)
        {
            return StringDigest(strSrc, DigestType.MD5);
        }

        public static byte[] StringDigest(string strSrc, DigestType dgType)
        {
            byte[] bytes = Encoding.Default.GetBytes(strSrc);
            return GetHashAlgorithmByType(dgType).ComputeHash(bytes);
        }
    }

    public enum DigestType : short
    {
        MD5 = 0,
        RIPEMD160 = 5,
        SHA1 = 1,
        SHA256 = 2,
        SHA384 = 3,
        SHA512 = 4
    }


    [Serializable]
    public class ByteStringUtil
    {
        public static byte[] ByteArrayFromHexStr(string hexStr)
        {
            try
            {
                if (string.IsNullOrEmpty(hexStr))
                {
                    return null;
                }
                if ((hexStr.Length % 2) != 0)
                {
                    return null;
                }
                if (hexStr.StartsWith("0x") || hexStr.StartsWith("0X"))
                {
                    hexStr = hexStr.Substring(2, hexStr.Length - 2);
                }
                byte[] buffer = new byte[hexStr.Length / 2];
                char[] chArray = hexStr.ToCharArray();
                int index = 0;
                for (int i = 0; index < chArray.Length; i++)
                {
                    buffer[i] = Convert.ToByte(string.Concat(new object[] { chArray[index], string.Empty, chArray[index + 1], string.Empty }), 0x10);
                    index += 2;
                }
                return buffer;
            }
            catch (Exception)
            {

                throw new ArgumentOutOfRangeException("ByteArrayFromHexStr出错");
            }

        }

        public static string ByteArrayToHexStr(byte[] bytdata)
        {
            try
            {
                if ((bytdata == null) || (bytdata.Length < 1))
                {
                    return string.Empty;
                }
                StringBuilder builder = new StringBuilder(0x100);
                foreach (byte num in bytdata)
                {
                    builder.Append(string.Format("{0:X2}", num));
                }
                return builder.ToString();
            }
            catch (Exception)
            {

                throw new ArgumentOutOfRangeException("ByteArrayToHexStr出错");
            }
        }
    }


    public class NetWork
    {
        /// <summary>
        ///      //获取到mac
        /// </summary>
        /// <param name="mac"></param>
        /// <returns></returns>
        public static List<string> GetMACs(out string mac)
        {
            string item = string.Empty;
            NetworkInterface[] allNetworkInterfaces = NetworkInterface.GetAllNetworkInterfaces();
            List<string> list = new List<string>();
            foreach (NetworkInterface interface2 in allNetworkInterfaces)
            {
                if (((interface2.NetworkInterfaceType != NetworkInterfaceType.Loopback) && (interface2.NetworkInterfaceType != NetworkInterfaceType.Tunnel)) && (interface2.OperationalStatus == OperationalStatus.Up))
                {
                    item = interface2.GetPhysicalAddress().ToString();
                    list.Add(item);
                }
            }
            mac = item;
            if (list.Count > 0)
            {
                return list;
            }
            return null;
        }
        /// <summary>
        /// 获取Ipv4
        /// </summary>
        /// <param name="LocalIP"></param>
        /// <returns></returns>
        public static string[] GetLocalIpv4(out string LocalIP)
        {
            LocalIP = string.Empty;
            IPAddress[] hostAddresses = Dns.GetHostAddresses(Dns.GetHostName());
            StringCollection strings = new StringCollection();
            foreach (IPAddress address in hostAddresses)
            {
                if (address.AddressFamily == AddressFamily.InterNetwork)
                {
                    LocalIP = address.ToString();
                    strings.Add(address.ToString());
                }
            }
            string[] array = new string[strings.Count];
            strings.CopyTo(array, 0);
            return array;
        }

        /// <summary>
        /// 获取本机IP
        /// </summary>
        /// <returns></returns>
        public static string GetLocalIp()
        {
            string hostname = Dns.GetHostName();
            IPHostEntry localhost = Dns.GetHostByName(hostname);
            IPAddress localaddr = localhost.AddressList[0];
            return localaddr.ToString();
        }
        
    }
}
